import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './index.css';

export default class Item extends Component {
  state = { mouse: false };

  static propTypes = {
    id: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
    done: PropTypes.bool.isRequired,
    updateTodo: PropTypes.func.isRequired,
    delTodo: PropTypes.func.isRequired
  };

  // 鼠标移入移出效果
  handleMouse = flag => {
    return () => {
      this.setState({ mouse: flag });
    };
  };

  // 复选框勾选
  handleCheck = id => {
    return e => {
      this.props.updateTodo(id, e.target.checked);
    };
  };

  // 删除
  handleDelete = (id) => {
    return () => {
      if(window.confirm("您确定删除吗？")) {
        this.props.delTodo(id)
      }
    }
  };

  render() {
    const { id, name, done } = this.props;
    const { mouse } = this.state;
    return (
      <div style={{ backgroundColor: mouse ? '#ddd' : 'white' }} className="todo-item" onMouseEnter={this.handleMouse(true)} onMouseLeave={this.handleMouse(false)}>
        <span className="item-left">
          <input type="checkbox" checked={done} name="" onChange={this.handleCheck(id)} />
          <span>{name}</span>
        </span>
        <button className="btn btn-danger" style={{ display: mouse ? 'block' : 'none' }} onClick={this.handleDelete(id)}>
          删除
        </button>
      </div>
    );
  }
}
